﻿using MediatR;
using Medical.Api.Write.Application.Command.DepartmentManagement.Recycling;
using Medical.Domain.DepartmentInfo;
using Medical.ErrorCode;
using Medical.Interstructrue.Base;
using Medical.Interstructrue;
using Microsoft.EntityFrameworkCore;

namespace Medical.Api.Write.Application.Handler.DepartmentManagement.Recycling
{
    /// <summary>
    /// 回收申请添加处理程序
    /// </summary>
    public class AddRecyclingCommandHandler : IRequestHandler<AddRecyclingCommands, ApiResult<int>>
    {
        private readonly ILogger<AddRecyclingCommandHandler> logger;
        private readonly IBaseRepository<RecyclingTable> recyclingRep;
        private readonly MedicalDbContext dbContext;

        /// <summary>
        /// 构造函数，注入所需依赖
        /// </summary>
        /// <param name="logger">日志记录器</param>
        /// <param name="recyclingRep">回收表仓储</param>
        /// <param name="dbContext">数据库上下文</param>
        public AddRecyclingCommandHandler(ILogger<AddRecyclingCommandHandler> logger, 
            IBaseRepository<RecyclingTable> recyclingRep, MedicalDbContext dbContext)
        {
            this.logger = logger;
            this.recyclingRep = recyclingRep;
            this.dbContext = dbContext;
        }

        /// <summary>
        /// 处理回收申请添加命令
        /// </summary>
        /// <param name="request">回收申请命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>API结果</returns>
        public async Task<ApiResult<int>> Handle(AddRecyclingCommands request, CancellationToken cancellationToken)
        {
            // 开启数据库事务
            using var transaction = await dbContext.Database.BeginTransactionAsync(cancellationToken);
            try
            {
                // 验证回收申请数据
                if (request.recyclingTable == null)
                {
                    logger.LogWarning("回收申请数据为空");
                    return new ApiResult<int>()
                    {
                         Code = ApiEnums.Fail,
                         Data = 1,
                         Msg = "回收申请数据不能为空"
                    }; 
                }
                
                // 设置默认值
                if (request.recyclingTable.ApplicationTime == default)
                {
                    request.recyclingTable.ApplicationTime = DateTime.Now;
                }
                
                // 设置BaseEntity的默认值
                request.recyclingTable.CreateTime = DateTime.Now;
                request.recyclingTable.IsDeleted = false;
                // Id 由数据库自动生成
                // CreateUserId 和 CreateUserName 可以通过当前用户上下文设置
                // UpdateTime, UpdateUserId, UpdateUserName 在创建时不需要设置

                // 添加回收申请
                recyclingRep.Create(request.recyclingTable);
                await dbContext.SaveChangesAsync(cancellationToken);
                
                // 提交事务
                await transaction.CommitAsync(cancellationToken);
                
                logger.LogInformation("成功添加回收申请，ID：{Id}", request.recyclingTable.Id);
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Success,
                    Data = request.recyclingTable.Id,
                    Msg = "成功添加回收申请"
                };
            }
            catch (Exception ex)
            {
                // 回滚事务
                await transaction.RollbackAsync(cancellationToken);
                
                logger.LogError(ex, "添加回收申请时发生错误：{Message}", ex.Message);
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Fail,
                    Data = 1,
                    Msg = "添加回收申请失败"
                };
            }
        }
    }
}
